<?php

namespace App\Controllers\Admin;
use Sentry,User,DB,Area,Wechat,Pub,Cache;
use App,PHPExcel;
use BaseController,View,Input,Form,Order,Customer,City,Notification,Redirect;
class CitiesController extends BaseController {

	/**
	 * Display a listing of the resource.
	 * GET /admin/cities
	 *
	 * @return Response
	 */
	public function index()
	{
		//



        $user = Sentry::getUser();

        // Check if the user has the 'admin' permission. Also,
        // multiple permissions may be used by passing an array
        if ($user->hasAccess('admin')){
            $myusers = User::where('permissions','{"city":1}')->get();
        }elseif($user->hasAccess('city')){
            if($user->city == 9){
                $myusers = User::where('permissions','{"section":1}')->where('father_id',$user->id)->get();
            }else{
                $myusers = User::where('permissions','{"section":1}')->where('city',$user->city)->get();
            }
        }elseif($user->hasAccess('section')){
            echo 3;
        }

        $METHOD = 'cities';
        $ACTION = 'index';


        

        return View::make('admin.cities.index',compact('METHOD','ACTION','myusers','user'));
	}

	/**
	 * Show the form for creating a new resource.
	 * GET /admin/cities/create
	 *
	 * @return Response
	 */
	public function create()
	{
		//
        $user = Sentry::getUser();
        $METHOD = 'cities';
        $ACTION = 'index';
        return View::make('admin.cities.create',compact('METHOD','ACTION','user'));
	}

	/**
	 * Store a newly created resource in storage.
	 * POST /admin/cities
	 *
	 * @return Response
	 */
	public function store()
	{
		//


        $user = Sentry::getUser();

        // Check if the user has the 'admin' permission. Also,
        // multiple permissions may be used by passing an array
        if ($user->hasAccess('admin')){

            $province = Area::where('name', Input::get('province'))->count();
            if($province != 0){
                $province = Area::where('name', Input::get('province'))->first();
                $province_id = $province->id;
                $city = Area::where('name', Input::get('city'))
                    ->where('father_id',$province_id)
                    ->count();
                if($city != 0){
                    $city = Area::where('name', Input::get('city'))
                        ->where('father_id',$province_id)
                        ->first();
                    $city_id = $city->id;
                }else{
                    $city_id = $this->create_city($province_id,Input::get('city'));
                }
            }else{
                $province_id = $this->create_province(Input::get('province'));
                $city_id = $this->create_city($province_id,Input::get('city'));
            }

            Sentry::getUserProvider()->create(array(
                'username'      => Input::get('username'),
                'mobile'      => Input::get('mobile'),
                'province'   => $province_id,
                'city'   => $city_id,
                'password' => Input::get('pwd'),
                'permissions' => ['city' => 1],
                'activated'  => 1,
            ));

            $adminUser  = Sentry::getUserProvider()->findByLogin(Input::get('mobile'));
            $adminGroup = Sentry::getGroupProvider()->findByName('City');
            $adminUser->addGroup($adminGroup);

//            Sentry::getGroupProvider()->create(array(
//                'name'        => $city_id
//            ));
        }elseif($user->hasAccess('city')){

            $area_id = $this->create_area($user->city ,Input::get('area'));
            Sentry::getUserProvider()->create(array(
                'username'      => Input::get('username'),
                'mobile'      => Input::get('mobile'),
                'province'   => $user->province,
                'city'   => $user->city,
                'password' => Input::get('pwd'),
                'activated'  => 1,
                'permissions' => ['section' => 1],
                'father_id' => $user->id,
                'area'=>$area_id
            ));


//            $adminUser  = Sentry::getUserProvider()->findByLogin(Input::get('mobile'));
//            $adminGroup = Sentry::getGroupProvider()->findByName($user->city);
//            $adminUser->addGroup($adminGroup);



            $areas = array();
            $xiaoqu = Input::get('xiaoqu');
            $xiaoqu = array_filter($xiaoqu);
            foreach($xiaoqu as $ar){
                $areas[] = array('name' => $ar, 'address'=>$user->province.$user->city.Input::get('area').$ar,'city_id'=>$user->city,'father_id'=>$area_id,'level'=>4);
            }

            DB::table('areas')->insert($areas);



        }elseif($user->hasAccess('section')){


        }




        return Redirect::route('admin.cities.index');
	}

	/**
	 * Display the specified resource.
	 * GET /admin/cities/{id}
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
		//
	}

	/**
	 * Show the form for editing the specified resource.
	 * GET /admin/cities/{id}/edit
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		//

        $user = User::find($id);
        $METHOD = 'cities';
        $ACTION = 'index';
        return View::make('admin.cities.edit',compact('METHOD','ACTION','user'));
	}

	/**
	 * Update the specified resource in storage.
	 * PUT /admin/cities/{id}
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{
		//
        $edituser = User::find($id);
//        echo $id;
//        echo Input::get('pwd');

        //重置用户密码
        // Find the user using the user email address
        $user = Sentry::findUserByLogin($edituser->mobile);

        // Get the password reset code
        $resetCode = $user->getResetPasswordCode();

        $user = Sentry::findUserById($id);

        // Check if the reset password code is valid
        if ($user->checkResetPasswordCode($resetCode))
        {
            // Attempt to reset the user password
            if ($user->attemptResetPassword($resetCode, Input::get('pwd')))
            {
                // Password reset passed
                $url = route('admin.cities.index');
                header("Content-Type: text/html;charset=utf-8");
                echo"<SCRIPT LANGUAGE='javascript'>alert('修改成功！');location.href='".$url."'</SCRIPT>";
            }
            else
            {
                // Password reset failed
                echo '修改失败';
            }
        }
        else
        {
            // The provided password reset code is Invalid
            echo '修改失败';
        }
        exit;
	}

	/**
	 * Remove the specified resource from storage.
	 * DELETE /admin/cities/{id}
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		//
        $user = User::find($id);
        $user->delete();

        return Redirect::route('admin.cities.index');
	}

    public function deleteit(){
        $id = Input::get('delete_id');
        $user = User::find($id);

        if($user->permissions == '{"city":1}'){
//            $area = Area::find($user->city);
//    //        if($area){
//            $area->delete();
    //        }

        }elseif($user->permissions == '{"section":1}'){
            DB::table('areas')->where('level',4)->where('father_id',$user->area)->delete();
            DB::table('areas')->where('level',3)->where('id',$user->area)->delete();
        }
        $user->delete();




        return Redirect::route('admin.cities.index');
    }


    public function maps(){

    }

    /**
     * ajax设置默认分销商
     * 当用户填写不存在小区时自动划分到默认分销商中
     */
    public function set_default(){
        $user = Sentry::getUser();
        $city_id = $user->city;

        $id = Input::get('id');
        $default_user = User::find($id);

        DB::table('users')
            ->where('city', $city_id)
            ->where('permissions', '{"section":1}')
            ->update(array('default' => 0));

        $default_user = User::find($id);
        $default_user->default = 1;
        $default_user->save();
    }

    public function xiaoqu(){
        $user = Sentry::getUser();
        if($_POST){
            $xiaoqu = Input::get('xiaoqu');
            $xiaoqu = array_filter($xiaoqu);
            $id = Input::get('id');

            $areas = array();
            $check =1;
            $enable = array();
            foreach($xiaoqu as $ar){
                $count = Area::where('name',$ar)->where('city_id',$user->city)->where('father_id','!=',$id)->count();
                if($count != 0){
                    $check = 0;
                    $enable[] = $ar;
                }

                $parents_count = Area::where('name',$ar)->where('city_id',$user->city)->where('father_id','=',$id)->count();

                if($parents_count == 0){
                    $areas[] = array('name' => $ar, 'address'=>$user->province.$user->city.$ar,'city_id'=>$user->city,'father_id'=>$id,'level'=>4);
                }
            }
            if($check == 0){
                echo implode(',',$enable).'已经存在';
                exit;
            }
            if (count($xiaoqu) != count(array_unique($xiaoqu))) {
                echo '有重复的小区';
                exit;
            }

//            DB::table('areas')->where('level',4)->where('father_id',$id)->delete();
            DB::table('areas')->insert($areas);
            return Redirect::route('admin.cities.index');

        }
        $id = Input::get('id');
        $METHOD = 'cities';
        $ACTION = 'index';
        $areas = Area::where('level',4)->where('father_id',$id)->where('city_id',$user->city)->get();
        return View::make('admin.cities.xiaoqu',compact('METHOD','ACTION','user','areas','id'));
    }

    public function create_city($province_id,$city){
        $area          = new Area;
        $area->name   = $city;
        $area->father_id    = $province_id;
        $area->level    = 2;
        $area->save();
        $city_id = $area->id;
        return $city_id;
    }

    public function create_province($province){
        $area          = new Area;
        $area->name   = $province;
        $area->father_id    = 0;
        $area->level    = 1;
        $area->save();
        $province_id = $area->id;
        return $province_id;
    }

    public function create_area($city_id,$areaname){
        $area          = new Area;
        $area->name   = $areaname;
        $area->father_id    = $city_id;
        $area->level    = 3;
        $area->save();
        $area_id = $area->id;
        return $area_id;
    }



    public function get_code(){
        $pub = Pub::find(1);
        if (Cache::has('token'))
        {
            //
            $value = Cache::get('token');
        }else{
            $value =  Wechat::get_access_token($pub->AppID,$pub->AppSecret);
            Cache::put('token', $value, 240);
        }
        $id = Input::get('id');
        $id = (int)$id;
        $true = $id;
        $arr['ticket'] = Wechat::get_pic($value,$true,1,false);
        if($arr['ticket'] == 'error'){
            $value =  Wechat::get_access_token($pub->AppID,$pub->AppSecret);
            Cache::put('token', $value, 240);
            $arr['ticket'] = Wechat::get_pic($value,$true,1,false);
        }
        echo '<img src="'.$arr['ticket'].'">';
    }

    /**
     * 导出粉丝excel
     */
    public function export(){


        $users = User::where('permissions','{"section":1}')->orderBy('province', 'ASC')->orderBy('city', 'ASC')->get();


        $this->_excel($users);
    }


    protected function _excel($users){

        require app_path().'/lib/Excel/PHPExcel.php';
        $objPHPExcel=new PHPExcel();
        $objPHPExcel->getProperties()->setCreator('http://www.jb51.net')
            ->setLastModifiedBy('http://www.jb51.net')
            ->setTitle('Office 2007 XLSX Document')
            ->setSubject('Office 2007 XLSX Document')
            ->setDescription('Document for Office 2007 XLSX, generated using PHP classes.')
            ->setKeywords('office 2007 openxml php')
            ->setCategory('Result file');
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1','分销商')
            ->setCellValue('B1','运营商')
            ->setCellValue('C1','省')
            ->setCellValue('D1','市')
            ->setCellValue('E1','粉丝数')
            ->setCellValue('F1','装机数')
            ->setCellValue('G1','小区数');

//        var_dump($list);
        $i = 2;
        foreach($users as $user){
            $father = $user->fathercity->username;
            if($father == ''){
                $father = ' ';
            }
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValueExplicit('A'.$i,$user->username,\PHPExcel_Cell_DataType::TYPE_STRING)
                ->setCellValueExplicit('B'.$i,$father,\PHPExcel_Cell_DataType::TYPE_STRING)
                ->setCellValue('C'.$i,$user->provincename->name)
                ->setCellValue('D'.$i,$user->cityname->name)
                ->setCellValue('E'.$i,$user->subscribe)
                ->setCellValue('F'.$i,$user->mount_count)
                ->setCellValue('G'.$i,$user->area_count);
            $i++;
        }

        $objPHPExcel->getActiveSheet()->setTitle('Sheet1');
        $objPHPExcel->setActiveSheetIndex(0);
        $filename=urlencode('粉丝统计').'_'.date('Y-m-dH');
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$filename.'.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');


        $objWriter->save('php://output');

    }

}